package com.djsblog.service.impl;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.djsblog.entity.Blog;
import com.djsblog.entity.Files;
import com.djsblog.entity.Mapping;
import com.djsblog.entity.PageBean;
import com.djsblog.entity.Type;
import com.djsblog.enums.Options;
import com.djsblog.service.BlogService;
import com.djsblog.util.LunceUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.tx.Tx;
/**
 * 博客事务接口实现
 * @author 但劲松
 *
 */
@Before(Tx.class)
public class BlogServiceImpl implements BlogService{

	public List<Blog> find(Blog s_blog, PageBean pageBean) {
		StringBuffer sql = new StringBuffer("select * from blog ");
		if(s_blog!=null){
			//删除标识
			if(StrKit.notBlank(s_blog.getDel()))
				sql.append(" and del='"+s_blog.getDel()+"'");
			//构建模糊查询标题
			if(StrKit.notBlank(s_blog.getTitle()))
				sql.append(" and title like '%"+s_blog.getTitle()+"%'");
			//时间倒序排序	
			if(s_blog.getCreated()!=null)
				sql.append(" order by created desc");
		}
		//分页
		if(pageBean != null) sql.append(" limit "+pageBean.getStart()+","+pageBean.getPageSize());
		return Blog.dao.find(sql.toString().replaceFirst(" and", " where"));
	}

	public Long count(Blog s_blog) {
		StringBuffer sql = new StringBuffer("select count(*) as total from blog ");
		if(s_blog!=null){
			//删除标识
			if(StrKit.notBlank(s_blog.getDel()))
				sql.append(" and del='"+s_blog.getDel()+"'");
			//构建模糊查询标题
			if(StrKit.notBlank(s_blog.getTitle()))
				sql.append(" and title like '%"+s_blog.getTitle()+"%'");
		}
		return Db.queryLong(sql.toString().replaceFirst(" and", " where"));
	}

	public boolean save(Blog blog,String[] type,String[] biaoqian,Long zhuanti) {
		try{
			boolean flag = true;
			if(blog.getPhoto()!=null) 
			{	//获取主图
				Files f = Files.dao.findById(blog.getPhoto());
				if(f.getId()!=null){
					//更新主图名称
					f.setName(blog.getTitle()+"的图片");
					f.setCreated(new Date());
					f.update();
				}
			}
			//判断是否为创建
			if(blog.getId()==null){
				flag=blog.save();
				//创建索引
				new LunceUtil().creatIndex(blog);
			}
			else{
				flag=blog.update();
				//修改索引
				new LunceUtil().updateIndex(blog);
			}
			//构建分类映射
			if(StrKit.notBlank(type)){
				String fa_flag = "";
				//删除旧的映射
				Db.update("delete from mapping where mapping_type='"+Options.BLOG_TYPE+"' and fatherId="+blog.getId());
				//构建分类映射
				for(String t:type){
					Mapping m = new Mapping();
					m.setFatherId(blog.getId());
					m.setSonId(Long.parseLong(t));
					m.setMappingType(Options.BLOG_TYPE);
					//查找父映射
					Type isFa=Type.dao.findById(t);
					if(!Options.G_FATHER.equals(isFa.getTypeType()))
					{
						//查看是否添加过这条父映射
						if(!fa_flag.contains(isFa.getTypeType())){
							Mapping m_fa = new Mapping();
							m_fa.setFatherId(blog.getId());
							m_fa.setSonId(Long.parseLong(isFa.getTypeType()));
							m_fa.setMappingType(Options.BLOG_TYPE);
							flag=m_fa.save();
							fa_flag+=isFa.getTypeType();
						}
					}else{
						//如果本身就是父映射那么，就马上记录添加过
						fa_flag+=t;
					}
					flag=m.save();
				}
			}
			//构建标签
			if(StrKit.notBlank(biaoqian)){
				//删除旧的映射
				Db.update("delete from mapping where mapping_type='"+Options.BLOG_BIAOQIAN+"' and fatherId="+blog.getId());
				for(String bq:biaoqian){
					//构建标签映射
					Mapping m = new Mapping();
					m.setFatherId(blog.getId());
					m.setMappingType(Options.BLOG_BIAOQIAN);
					//查看标签是否存在
					Type t = Type.dao.findFirst("select * from type "+"where name='"+bq+"' and type_type='"+Options.G_BIAOQIAN+"'");
					//不存在就创建新标签
					if(t==null){
						t = new Type();
						t.setName(bq);
						t.setTypeType(Options.G_BIAOQIAN);
						flag=t.save();
					}
					m.setSonId(t.getId());
					flag=m.save();
				}
			}
			//构建专题
			if(!new Long(0).equals(zhuanti)){
				//删除旧的映射
				Db.update("delete from mapping where mapping_type='"+Options.BLOG_ZHUANTI+"' and fatherId="+blog.getId());
				Mapping m = new Mapping();
				m.setFatherId(blog.getId());
				m.setSonId(zhuanti);
				m.setMappingType(Options.BLOG_ZHUANTI);
				m.save();
			}
			return flag;
			}catch(Exception e){
				try {
					//执行失败回滚事务
					DbKit.getConfig().getConnection().rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				} 
			}
			return false;
	}

	public Blog getById(Long id) {
		return Blog.dao.findById(id);
	}

	public boolean deleteOrComeback(Long id, String del) {
		try{
			Blog blog = new Blog();
			blog.setId(id);
			blog.setDel(del);
			LunceUtil l = new LunceUtil();
			//删除对应索引
			if("true".equals(del)){
				l.deleteIndex(id.toString());
			}else{
				//恢复对应索引
				Blog b = Blog.dao.findById(id);
				l.creatIndex(b);
			}
			return blog.update();
		}catch(Exception e){
			try {
				//执行失败回滚事务
				DbKit.getConfig().getConnection().rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			} 
		} 
		return false;
	}

	public boolean updateThings(Long id, String uOlOc) {
		try{
			Blog blog = Blog.dao.findById(id);
			if("up".equals(uOlOc)){
				Integer upOlow = blog.getVoteUp();
				blog.setVoteUp(++upOlow);
			}else if("low".equals(uOlOc)){
				Integer upOlow = blog.getVoteLow();
				blog.setVoteLow(++upOlow);
			}else{
				Integer upOlow = blog.getClick();
				blog.setClick(++upOlow);
			}
			return blog.update();
			
		}catch(Exception e){
			try {
				//执行失败回滚事务
				DbKit.getConfig().getConnection().rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			} 
		} 
		return false;
	}

	public boolean addComment(Long blogId) {
		try{
			Blog blog = Blog.dao.findById(blogId);
			Integer count = blog.getCommentCount();
			blog.setCommentCount(++count);
			return blog.update();
		}catch(Exception e){
			try {
				//执行失败回滚事务
				DbKit.getConfig().getConnection().rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			} 
		} 
		return false;
	}


}
